package com.kly.springbootinit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kly.springbootinit.common.ErrorCode;
import com.kly.springbootinit.common.UserContext;
import com.kly.springbootinit.exception.ThrowUtils;
import com.kly.springbootinit.mapper.PaymentMapper;
import com.kly.springbootinit.model.dto.payment.PaymentAddRequest;
import com.kly.springbootinit.model.entity.Orders;
import com.kly.springbootinit.model.entity.Payment;
import com.kly.springbootinit.model.entity.User;
import com.kly.springbootinit.model.enums.OrderStatusEnum;
import com.kly.springbootinit.model.enums.PaymentMethodEnum;
import com.kly.springbootinit.model.enums.PaymentStatus;
import com.kly.springbootinit.model.vo.PaymentVO;
import com.kly.springbootinit.service.OrderService;
import com.kly.springbootinit.service.PaymentService;
import com.kly.springbootinit.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author admin
 * @description 针对表【payment(支付记录表)】的数据库操作Service实现
 * @createDate 2025-05-21 14:34:09
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment>
        implements PaymentService {

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;


    @Override
    public PaymentVO createPayment(PaymentAddRequest paymentAddRequest) {
        ThrowUtils.throwIf(paymentAddRequest == null, ErrorCode.PARAMS_ERROR);
        Long orderId = paymentAddRequest.getOrderId();
        // 判断订单是否存在
        Orders ordersDb = orderService.getById(orderId);
        ThrowUtils.throwIf(ordersDb == null, ErrorCode.PARAMS_ERROR, "订单不存在");
        BigDecimal amount = paymentAddRequest.getAmount();

        Payment payment = new Payment();
        payment.setOrderId(orderId);
        payment.setAmount(amount);
        // 保存支付记录
        Long userId = UserContext.getUser().getId();
        if(paymentAddRequest.getUserId() == null) {
            payment.setUserId(userId);
        }
        synchronized (userId.toString().intern()) {
            this.save(payment);
        }
        PaymentVO paymentVO = BeanUtil.copyProperties(payment, PaymentVO.class);
        // 查询用户
        User user = userService.getById(userId);
        paymentVO.setUser(userService.getUserVO(user));
        return paymentVO;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public PaymentVO payPayment(Long id, String payMethod) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        Payment paymentDb = getById(id);
        ThrowUtils.throwIf(paymentDb == null, ErrorCode.PARAMS_ERROR, "支付记录不存在");
        ThrowUtils.throwIf(!paymentDb.getStatus().equals(PaymentStatus.UNPAID.getCode()), ErrorCode.PARAMS_ERROR, "支付记录已支付");
        PaymentMethodEnum paymentMethodEnum = PaymentMethodEnum.fromCode(payMethod);
        ThrowUtils.throwIf(paymentMethodEnum == null, ErrorCode.PARAMS_ERROR);
        paymentDb.setPaymentMethod(paymentMethodEnum.getCode());
        paymentDb.setStatus(PaymentStatus.PAID.getCode()); // 支付成功
        paymentDb.setUpdateTime(new Date());
        updateById(paymentDb); // 更新支付记录
        // 更新订单状态
        boolean update = orderService.lambdaUpdate()
                .eq(Orders::getId, paymentDb.getOrderId())
                .eq(Orders::getStatus, OrderStatusEnum.UNPAID.getCode())
                .set(Orders::getStatus, OrderStatusEnum.PAID.getCode())
                .set(Orders::getStartTime, new Date())
                .set(Orders::getUpdateTime, new Date())
                .update();
        ThrowUtils.throwIf(!update, ErrorCode.PARAMS_ERROR, "更新订单状态失败");

        PaymentVO paymentVO = BeanUtil.copyProperties(paymentDb, PaymentVO.class);
        return paymentVO;
    }
}




